<template>
  <el-form
    ref="form"
    :model="form"
    style="width: 400px; margin-top:40px"
    label-width="80px"
    :rules="rules"
  >
    <el-form-item label="姓名: " prop="username">
      <el-input v-model="form.username"></el-input>
    </el-form-item>
    <el-form-item label="密码: " prop="password">
      <el-input type="password" v-model="form.password"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="updateEmployee">更新</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      userId: this.$route.params.id,
      form: {
        username: "",
        password: ""
      },
      result: {},
      rules: {
        username: [
          { required: true, message: "姓名必须填写", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码必须填写", trigger: "blur" },
          { min: 6, max: 9, message: "密码必须长度在6到9位", trigger: "blur" }
        ]
      }
    };
  },
  mounted() {
    this.getEmployeeById(this.userId);
  },
  methods: {
    //获取员工
    async getEmployeeById(id) {
      let result = await this.$api.employee.getEmployeeById(id);
      console.log(result);
      this.result = result;
      this.form = {
        username: result.username
      };
    },

    //更新员工
    updateEmployee() {
      this.$refs["form"].validate().then(async () => {
        try {
          let result = await this.$api.employee.saveEmployeeById(this.userId, {
            id: this.userId,
            ...this.form
          });
          this.$message.success("修改成功!");
        } catch (error) {
          this.$message.error("修改失败!");
        }
      });
    },
    //取消
    cancel() {
      this.form = {
        username: this.result.username,
        password: ""
      };
    }
  }
};
</script>

<style>
</style>